package com.longcai.mq.consumer;

import com.longcai.advice.RollBackExecption;
import com.longcai.bean.ApiResult;
import com.longcai.config.rabbitmq.QueueConfig;
import com.longcai.constants.OrderConstants;
import com.longcai.entity.order.ClyjGoodsOrderDetails;
import com.longcai.mapper.ClyjGoodsOrderDetailsMapper;
import com.longcai.mapper.ClyjGoodsOrderInfoMapper;
import com.longcai.service.impl.ClyjGoodsOrderDetailsServiceImpl;
import com.longcai.util.UUIDUtil;
import com.longcai.vo.ClyjGoodsOrderDetailsVo;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 订单消息消费者
 *
 * @author zhaojie
 * @Title: DealOrderQueueConsumer
 * @ProjectName clyj-electricity
 * @Description: TODO
 * @date 2019/4/2317:17
 */
@Component
public class DealOrderQueueConsumer {

    private static final Logger logger = LoggerFactory.getLogger(ClyjGoodsOrderDetailsServiceImpl.class);

    @Autowired
    private ClyjGoodsOrderDetailsMapper clyjGoodsOrderDetailsMapper;
    @Autowired
    private ClyjGoodsOrderInfoMapper clyjGoodsOrderInfoMapper;

    /**
     * 订单消费
     *
     * @param orderDetailsVo
     * @param channel
     * @throws Exception
     */
    @RabbitListener(queues = {QueueConfig.QUEUE_NAME1}, containerFactory = "rabbitListenerContainerFactory")
    @RabbitHandler
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ApiResult<?> onMessage(ClyjGoodsOrderDetailsVo orderDetailsVo, Message message, Channel channel) throws Exception {
        logger.info("------->>>>>order节点启动了消费者");
        // 采用手动应答模式, 手动确认应答更为安全稳定
        // ack返回false，并重新回到队列，api里面解释得很清楚
        if (orderDetailsVo == null) {
            logger.error("------->>>>>订单队列的值不存在");
            // 拒绝消息
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            return ApiResult.fail("订单队列不存在");
        }
        try {
            // 处理消息
            logger.info("------->>>>>order接收到消息" + orderDetailsVo.getClyjGoodsOrderDetails().toString());
            // 创建订单
            this.createClyjGoodsOrderDetails(orderDetailsVo);
            // 确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            logger.error("------->>>>>order订单消费成功");
            return ApiResult.fail("订单创建成功");
        } catch (Exception e) {
            logger.error("------->>>>>order订单消费失败", e);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            throw new RollBackExecption("订单创建处理失败");
        }
    }

    /**
     * 创建订单
     *
     * @param orderDetailsVo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void createClyjGoodsOrderDetails(ClyjGoodsOrderDetailsVo orderDetailsVo) {
        List<ClyjGoodsOrderDetails> clyjGoodsOrderDetails = orderDetailsVo.getClyjGoodsOrderDetails();
        clyjGoodsOrderDetails.stream().forEach(o -> {
            // 创建订单
            this.clyjGoodsOrderInfoMapper.insertSelective(o);
            // 创建订单明细
            this.clyjGoodsOrderDetailsMapper.insertSelective(o);
            // 附近多商品下单
            boolean result = (o.getOrderType() != null && OrderConstants.ORDER_TYPE_2 == o.getOrderType()) && orderDetailsVo.getDetails().size() != 0;
            if (result == true) {
                List<ClyjGoodsOrderDetails> details = orderDetailsVo.getDetails();
                for (ClyjGoodsOrderDetails detail : details) {
                    ClyjGoodsOrderDetails orderDetails = new ClyjGoodsOrderDetails();

                    orderDetails = detail;
                    orderDetails.setId((long) UUIDUtil.uuid().hashCode());
                    orderDetails.setPTradeNo(o.getTradeNo());
                    orderDetails.setUserId(o.getUserId());
                    orderDetails.setShopsId(o.getShopsId());
                    orderDetails.setShopsName(o.getShopsName());
                    orderDetails.setReceiver(o.getReceiver());
                    orderDetails.setReceiverAddress(o.getReceiverAddress());
                    orderDetails.setReceiverPhone(o.getReceiverPhone());
                    orderDetails.setCreateTime(System.currentTimeMillis());
                    orderDetails.setUpdateTime(System.currentTimeMillis());
                    orderDetails.setPayTime(System.currentTimeMillis());

                    this.clyjGoodsOrderDetailsMapper.insertSelective(orderDetails);
                }
            }
        });
    }
}